package com.da.lon.wang.xlg.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.bean.ModifyPhotoBean;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.imgupload.ImageInfo;
import com.da.lon.wang.xlg.util.LogUtils;
import com.da.lon.wang.xlg.util.MyBitmapFactory;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.ToastUtils;
import com.da.lon.wang.xlg.util.WebViewUtil;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.da.lon.wang.xlg.view.RoundImageView;
import com.umeng.analytics.MobclickAgent;

import net.tsz.afinal.http.AjaxParams;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Calendar;
import java.util.List;

public class SettingInfoActivity extends BaseActivity implements
        OnClickListener {
    RelativeLayout set_log;
    RelativeLayout set_nink_name;
    RelativeLayout set_gender;
    RelativeLayout set_birthday;
    RoundImageView setting_log;
    TextView setting_nink_name;
    TextView setting_gender;
    TextView setting_birthday;
    AlertDialog dialog;
    ImageButton left;
    TextView title;
    int b_year;
    int b_month;
    int b_day;
    private String log;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting_info_activity);
        setting_log = (RoundImageView) findViewById(R.id.setting_log);
        log = PreferenceUtils.getInstance().getSettingStr(
                PreferencesConfig.HEAD_LOG, "");
        if (null != log && !log.trim().isEmpty()) {
//			MyApplication.loadImageAndResize(this, log, setting_log, 90, 90);
            MyApplication.loadImageByPicasso(this, log, null, setting_log, 90, 90, 1);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private void initView() {
        try {
            set_log = (RelativeLayout) findViewById(R.id.set_log);
            set_nink_name = (RelativeLayout) findViewById(R.id.set_nink_name);
            set_gender = (RelativeLayout) findViewById(R.id.set_gender);
            set_birthday = (RelativeLayout) findViewById(R.id.set_birthday);

            setting_nink_name = (TextView) findViewById(R.id.setting_nink_name);
            setting_gender = (TextView) findViewById(R.id.setting_gender);
            setting_birthday = (TextView) findViewById(R.id.setting_birthday);
            left = (ImageButton) findViewById(R.id.ouka_home_buyer_left);
            title = (TextView) findViewById(R.id.title);
            title.setText(R.string.my_account);

            left.setOnClickListener(this);
            set_log.setOnClickListener(this);
            set_nink_name.setOnClickListener(this);
            set_gender.setOnClickListener(this);
            set_birthday.setOnClickListener(this);

            String nink_name = PreferenceUtils.getInstance().getSettingStr(
                    PreferencesConfig.USER_NAME, "");
            String gender = PreferenceUtils.getInstance().getSettingStr(
                    PreferencesConfig.USER_SEX, "");
            String birthday = PreferenceUtils.getInstance().getSettingStr(
                    "birthday", "");

            if (nink_name != null && !"".equals(nink_name)) {
                setting_nink_name.setText(nink_name);
            }
            String genderStr = "";
            if (gender != null && !"".equals(gender)) {
                switch (gender) {
                    case "0":
                        genderStr = getString(R.string.female);
                        break;
                    case "1":
                        genderStr = getString(R.string.male);
                        break;
                    case "2":
                        genderStr = getString(R.string.unknown);
                        break;
                }
                setting_gender.setText(genderStr);
            }
            if (birthday != null && !"".equals(birthday)) {
                setting_birthday.setText(birthday);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        initView();
    }

    /**
     * 更改头像
     *
     * @param head_path
     */
    private void updateLog(String head_path) throws FileNotFoundException {
        try {
            HttpLoader<ModifyPhotoBean> httpLoader = new HttpLoader<ModifyPhotoBean>(
                    this, XLGConstants.URL + "User-userhpedit",
                    ModifyPhotoBean.class);
            AjaxParams params = new AjaxParams();
            params.put("token", XLGDataUtils.encrypt2MD5("User" + "2015#$%"
                    + "userhpedit"));
            params.put(
                    "id",
                    PreferenceUtils.getInstance().getSettingStr(
                            PreferencesConfig.USER_ID, ""));
            params.put("device_type", "1");

            File saveMyBitmap = MyBitmapFactory.saveMyBitmap(
                    "compressImage.jpg",
                    MyBitmapFactory.getMatrixImage(head_path));
            if (saveMyBitmap == null) {
                return;
            }
            params.put("file", saveMyBitmap);
            params.put(
                    "deviceId",
                    PreferenceUtils.getInstance().getSettingStr(
                            PreferencesConfig.DEVICE_ID, ""));
            params.put(
                    "user_key",
                    PreferenceUtils.getInstance().getSettingStr(
                            PreferencesConfig.USER_KEY, ""));
            httpLoader
                    .setManagerListener(new OnWebLoadListener<ModifyPhotoBean>() {

                        @Override
                        public void OnStart() {
                            // TODO Auto-generated method stub
                            showDialog();
                        }

                        @Override
                        public void OnError(String error) {
                            // TODO Auto-generated method stub
                            dismissDialog();

                        }

                        @Override
                        public void onSuccess(ModifyPhotoBean t) {
                            // TODO Auto-generated method stub
                            if (t != null && t.getCode().equals("000000")) {
                                ToastUtils.showShort(SettingInfoActivity.this,
                                        t.getMessage());
                            }
                            dismissDialog();
                        }
                    });

            httpLoader.loadData(params);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.set_log:
                HomeActivity.uploadMaxNum = 1;
                MyApplication.getInstance().imageInfos.clear();
                WebViewUtil.showsettingHeadLogDialog(this);
                break;
            case R.id.set_nink_name:
                intent = new Intent(this, UpdateNinkNameActivity.class);
                break;
            case R.id.set_gender:
                intent = new Intent(this, UpdateGenderActivity.class);
                break;
            case R.id.set_birthday:
                try {
                    showDatePickerDialog();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                break;
            case R.id.ouka_home_buyer_left:
                finish();
                break;
            default:
                break;
        }
        if (intent != null) {
            startActivity(intent);
        }
    }

    /**
     * 显示日期选择器
     */
    public void showDatePickerDialog() throws Exception {
        final AlertDialog dialog = new AlertDialog.Builder(this).setTitle("")
                .setMessage("").create();
        View view = LayoutInflater.from(this).inflate(
                R.layout.date_picker_choise_dialog, null);
        Button cancle = (Button) view.findViewById(R.id.cancle);
        Button sure = (Button) view.findViewById(R.id.sure);
        DatePicker picker = (DatePicker) view.findViewById(R.id.date_picker);
        Calendar calendar = Calendar.getInstance();
        final int year1 = calendar.get(Calendar.YEAR);
        final int monthOfYear1 = calendar.get(Calendar.MONTH) + 1;
        final int dayOfMonth1 = calendar.get(Calendar.DAY_OF_MONTH);
        int tempy = Integer.parseInt(PreferenceUtils.getInstance()
                .getSettingStr("birth_year", "1990"));
        int tempm = Integer.parseInt(PreferenceUtils.getInstance()
                .getSettingStr("birth_month", "1")) - 1;
        int tempd = Integer.parseInt(PreferenceUtils.getInstance()
                .getSettingStr("birth_day", "1"));
        b_year = tempy;
        b_month = tempm + 1;
        b_day = tempd;

        picker.init(tempy, tempm, tempd, new OnDateChangedListener() {

            public void onDateChanged(DatePicker view, int year,
                                      int monthOfYear, int dayOfMonth) {
                b_year = year;
                b_month = monthOfYear + 1;
                b_day = dayOfMonth;
            }
        });
        cancle.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        sure.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (b_year == 0) {
                    b_year = 1900;
                }
                if (b_month == 0) {
                    b_month = 1;
                }
                if (b_day == 0) {
                    b_day = 1;
                }
                boolean flg = true;
                if (b_year > year1) {
                    flg = false;
                } else if (b_year == year1 && b_month > monthOfYear1) {
                    flg = false;
                } else if (b_month == monthOfYear1 && b_day > dayOfMonth1) {
                    flg = false;
                }

                if (flg) {
                    HttpLoader<ModifyPhotoBean> httpLoader = new HttpLoader<ModifyPhotoBean>(
                            SettingInfoActivity.this, XLGConstants.URL
                            + "/User-userinfoedit",
                            ModifyPhotoBean.class);
                    AjaxParams params = new AjaxParams();
                    params.put("token", XLGDataUtils.encrypt2MD5("User"
                            + "2015#$%" + "userinfoedit"));
                    params.put("id", PreferenceUtils.getInstance()
                            .getSettingStr(PreferencesConfig.USER_ID, ""));
                    params.put("device_type", "1");
                    params.put("deviceId", PreferenceUtils.getInstance()
                            .getSettingStr(PreferencesConfig.DEVICE_ID, ""));
                    params.put("user_key", PreferenceUtils.getInstance()
                            .getSettingStr(PreferencesConfig.USER_KEY, ""));
                    params.put("sex", PreferenceUtils.getInstance()
                            .getSettingStr(PreferencesConfig.USER_SEX, ""));
                    params.put("birth_year", b_year + "");
                    params.put("birth_month", b_month + "");
                    params.put("birth_day", b_day + "");
                    params.put("nickname", PreferenceUtils.getInstance()
                            .getSettingStr(PreferencesConfig.USER_NAME, ""));
                    httpLoader.loadData(params);
                    PreferenceUtils.getInstance().SetSettingString(
                            "birth_year", b_year + "");
                    PreferenceUtils.getInstance().SetSettingString(
                            "birth_month", b_month + "");
                    PreferenceUtils.getInstance().SetSettingString("birth_day",
                            b_day + "");
                    PreferenceUtils.getInstance().SetSettingString("birthday",
                            b_year + "年" + b_month + "月" + b_day + "日");
                    setting_birthday.setText(b_year + "年" + b_month + "月"
                            + b_day + "日");
                } else {
                    Toast.makeText(SettingInfoActivity.this, "日期不能大于今天",
                            Toast.LENGTH_SHORT).show();
                }
                dialog.dismiss();
            }
        });
        dialog.show();
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.xlg_image_choose_dialog_style);
        dialog.setCanceledOnTouchOutside(true);
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) this).getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (dm.widthPixels);
        dialog.getWindow().setAttributes(lp);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        try {
            switch (requestCode) {
                case 2000:
                    if (resultCode == RESULT_OK) {
                        String photoPath = WebViewUtil.getPhotoPath();

                        setting_log.setImageBitmap(MyBitmapFactory
                                .getMatrixImage(photoPath));
                        updateLog(photoPath);
                    } else if (resultCode == RESULT_CANCELED) {
                        LogUtils.v("取消拍照了！");
                    } else {

                    }
                    break;
                case 1000:
                    if (resultCode == RESULT_OK) {
                        LogUtils.v("相册选择取消拍照了！");
                    } else if (resultCode == RESULT_CANCELED) {
                        List<ImageInfo> imageInfos = MyApplication.getInstance().imageInfos;
                        if (imageInfos != null && imageInfos.isEmpty()) {
                            return;
                        }
                        setting_log.setImageBitmap(MyBitmapFactory
                                .getMatrixImage(imageInfos.get(0).path));
                        updateLog(imageInfos.get(0).path);
                    } else {

                    }
                    break;

                default:
                    break;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}
